package com.ai.dmc.utils.bean;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ai.dmc.utils.string.StringUtil;

/**
 * 
 * <p>Title: BeanHelper.java</p>
 * <p>Description:  Bean的工具类，目前提供了bean转化为map的操作；<br/>
 * 更多bean的方法，请参见 org.apache.commons.BeanUtils
 * org.springframework.beans.BeanUtils</p>
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company: 亚信科技（中国）有限公司</p>
 * @author chenhui2
 * @version 1.0 
 *
 */
@SuppressWarnings("unchecked")
public class BeanHelper {

	private static Log log = LogFactory.getLog(BeanHelper.class);
	
	// 不进行转换的字段
	private List<String> excludeFields = new ArrayList<String>();

	/**
	 * 不需要过滤字段的构造函数
	 * 
	 */
	public BeanHelper() {
	}

	/**
	 * 构造函数，设置在将Bean转化为Map是需要过滤的字段名称的集合
	 * @param _excludeFields
	 */
	public BeanHelper(List _excludeFields) {
		this.excludeFields = _excludeFields;
		// 默认排除class和parent
		this.excludeFields.add("class");
		this.excludeFields.add("parent");
	}

	/**
	 * bean to map <br/>
	 * map to bean参见BeanUtils.populate方法
	 * 
	 * @param obj
	 * @return
	 * @throws IntrospectionException
	 */
	public Map beanToMap(Object bean) throws IntrospectionException {
		Map<String, String> map = new HashMap<String, String>();
		BeanInfo bi = Introspector.getBeanInfo(bean.getClass());
		PropertyDescriptor[] pds = bi.getPropertyDescriptors();
		for (int i = 0; i < pds.length; i++) {
			String propName = pds[i].getName();
			
			if (this.excludeFields.contains(propName)) {
				continue;
			}
			try {
				String propValue = BeanUtils.getSimpleProperty(bean, propName);
				if (StringUtil.isNotEmpty(propValue)) {
					map.put(propName, propValue);
				}
			} catch (Exception e) {
			}
		}
		return map;
	}

	/**
	 * 打印map信息
	 * @param map
	 * void
	 *
	 */
	public static void printMap(Map map) {
		StringBuffer sb = new StringBuffer("");
		// 测试：打印参数信息
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			String value = ((String) map.get(key));
			sb.append("[" + key + "]=[" + value + "]");
		}
		// 测试：打印参数信息end
		log.debug("---------" + sb);
	}

	public List<String> getExcludeFields() {
		return excludeFields;
	}

	public void setExcludeFields(List<String> excludeFields) {
		this.excludeFields = excludeFields;
	}
}
